package com.wondream.myframework.app.common.util.email;

import org.apache.commons.lang3.StringUtils;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.mail.internet.MimeUtility;
import java.io.File;
import java.util.Properties;

public class SendEmailUtils {

    /**
     * 发送邮件
     * 
     * @param subject
     *            邮件主题
     * @param sendHtml
     *            邮件内容
     * @param receiveUser
     *            收件人地址
     * @param attachment
     *            附件
     */
    private static int doSendHtmlEmail(boolean isDebug, String mailHost, String userName, String userPwd, String receiveUser, String subject, String sendHtml, File attachment) {
        int result = -1;
        Transport transport = null;
        try {
            Properties properties = new Properties();
            properties.put("mail.smtp.host", mailHost);
            properties.put("mail.smtp.auth", "true");
            properties.put("mail.sender.username", userName);
            properties.put("mail.sender.password", userPwd);
            Session session = Session.getInstance(properties);
            session.setDebug(isDebug);// 开启后有调试信息
            MimeMessage message = new MimeMessage(session);
            // 发件人
            InternetAddress from = new InternetAddress(userName);
            message.setFrom(from);

            // 收件人
            InternetAddress to = new InternetAddress(receiveUser);
            message.setRecipient(Message.RecipientType.TO, to);

            // 邮件主题
            message.setSubject(subject);

            // 向multipart对象中添加邮件的各个部分内容，包括文本内容和附件
            Multipart multipart = new MimeMultipart();

            // 添加邮件正文
            BodyPart contentPart = new MimeBodyPart();
            contentPart.setContent(sendHtml, "text/html;charset=UTF-8");
            multipart.addBodyPart(contentPart);

            // 添加附件的内容
            if (attachment != null) {
                BodyPart attachmentBodyPart = new MimeBodyPart();
                DataSource source = new FileDataSource(attachment);
                attachmentBodyPart.setDataHandler(new DataHandler(source));

                // 网上流传的解决文件名乱码的方法，其实用MimeUtility.encodeWord就可以很方便的搞定
                // 这里很重要，通过下面的Base64编码的转换可以保证你的中文附件标题名在发送时不会变成乱码
                // sun.misc.BASE64Encoder enc = new sun.misc.BASE64Encoder();
                // messageBodyPart.setFileName("=?GBK?B?" +
                // enc.encode(attachment.getName().getBytes()) + "?=");

                // MimeUtility.encodeWord可以避免文件名乱码
                attachmentBodyPart.setFileName(MimeUtility.encodeWord(attachment.getName()));
                multipart.addBodyPart(attachmentBodyPart);
            }

            // 将multipart对象放到message中
            message.setContent(multipart);
            // 保存邮件
            message.saveChanges();

            transport = session.getTransport("smtp");
            // smtp验证，就是你用来发邮件的邮箱用户名密码
            transport.connect(mailHost, userName, userPwd);
            // 发送
            transport.sendMessage(message, message.getAllRecipients());
            result = 0;
            System.out.println("send success!");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (transport != null) {
                try {
                    transport.close();
                } catch (MessagingException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    public static int sendEmail(String mailSmtpHost, String mailSenderUsername, String mailSenderPassword, String mailReceiverUsername, String mailSubject, String mailTemplatePath,
            String mailTemplateFile, String mailCustId, String mailCustName, String mailZipPwd, String mailAffix,String pfxPwd) throws Exception {
        if (StringUtils.isEmpty(mailSmtpHost)) {
            throw new Exception("mailSmtpHost:邮件服务器地址为空");
        }
        if (StringUtils.isEmpty(mailSenderUsername)) {
            throw new Exception("mailSenderUsername:邮件服务器用户名为空");
        }
        if (StringUtils.isEmpty(mailReceiverUsername)) {
            throw new Exception("mailReceiverUsername:邮件服务器接受者为空");
        }
        if (StringUtils.isEmpty(mailSubject)) {
            throw new Exception("mailSubject:邮件服务器主题为空");
        }
        if (StringUtils.isEmpty(mailTemplatePath)) {
            throw new Exception("mailTemplatePath:邮件服务器目录为空");
        }
        if (StringUtils.isEmpty(mailTemplateFile)) {
            throw new Exception("mailTemplateFile:邮件服务器文件为空");
        }
        if (StringUtils.isEmpty(mailCustId)) {
            throw new Exception("mailCustId:用户（商户编号）为空");
        }
        if (StringUtils.isEmpty(mailCustName)) {
            throw new Exception("mailCustName:用户名称（商户名称）为空");
        }
        if (StringUtils.isEmpty(mailZipPwd)) {
            throw new Exception("mailZipPwd:邮件服务器压缩密码为空");
        }
        if (StringUtils.isEmpty(mailAffix)) {
            throw new Exception("mailAffix:邮件服务器附件为空");
        }
        if (StringUtils.isEmpty(pfxPwd)) {
            throw new Exception("pfxPwd:商户私钥密码为空");
        }
        String mailContent = FreeMarkerUtils.generaotr(mailTemplatePath, mailTemplateFile, mailCustId, mailCustName, mailZipPwd,pfxPwd);
        File mailAffixFile = new File(mailAffix);
        int ret = doSendHtmlEmail(true, mailSmtpHost, mailSenderUsername, mailSenderPassword, mailReceiverUsername, mailSubject, mailContent, mailAffixFile);
        return ret;
    }

    public static int sendEmailTo(String mailSmtpHost, String mailSenderUsername, String mailSenderPassword,
            String mailReceiverUsername, String mailSubject, String mailContent, String mailAffix)
            throws Exception {
        if (StringUtils.isEmpty(mailSmtpHost)) {
            throw new Exception("sendEmail:邮件服务器地址为空");
        }
        if (StringUtils.isEmpty(mailSenderUsername)) {
            throw new Exception("sendEmail:邮件服务器用户名为空");
        }
        if (StringUtils.isEmpty(mailReceiverUsername)) {
            throw new Exception("sendEmail:邮件服务器接受者为空");
        }
        if (StringUtils.isEmpty(mailSubject)) {
            throw new Exception("sendEmail:邮件服务器主题为空");
        }
        if (StringUtils.isEmpty(mailContent)) {
            throw new Exception("sendEmail:邮件服务器内容为空");
        }
        File mailAffixFile = null;
        if (!StringUtils.isEmpty(mailAffix)) {
            mailAffixFile = new File(mailAffix);
        }
        int ret = doSendHtmlEmail(true, mailSmtpHost, mailSenderUsername, mailSenderPassword, mailReceiverUsername, mailSubject, mailContent, mailAffixFile);
        return ret;
    }

    public static void main(String[] args) throws Exception {
        SendEmailUtils.sendEmail("smtp.52bill.com", "cailongfei@52bill.com", "######", "cailongfei@52bill.com", "测试邮件", "E:/newhlw/hlw-bui/WebRoot/mailftl/", "mail.ftl", "bianhao", "测试商户", "mima", "D:\\pfx\\100000000131\\100000000131.zip","1234567");
    }
}
